package com.sansui.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @name: LogAspect
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-03-16 22:15
 **/

@Aspect
@Component
public class LogAspect {


    /*
    * @Aspect 定义切面类，加上@Aspect、@Component注解；
    * @Component 组件扫描
    * */

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //定义一个切面  规定拦截哪些类  这里定义拦截所有控制器类
    @Pointcut("execution(* com.sansui.blog.controller.*.*(..))")
    public void log() {}

    @Before("log()")     //在切面执行前执行
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString(); //获取请求的url
        String ip = request.getRemoteAddr(); //获取请求的IP
        //获取调用的方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();//获取请求的参数

        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);

        logger.info("requestLog : {}",requestLog);

    }

    @After("log()")  //在切面执行后执行
    public void doAfter(){
//        logger.info("---------------__________当当当当相应完毕输出测试_________--------------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result) {
        logger.info("result : {}",result);
    }

    /**
     * 需要的拦截的日志信息
     * 组成一个内部类
     */
    private class RequestLog{
        private String url;//请求路径
        private String ip; //访客ip
        private String classMethod; //调用的方法
        private Object[] args; //请求参数

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }


}
